package cn.wenzy.aurora.framework.support.i18n.serializer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.wenzy.aurora.framework.support.i18n.annotation.I18nField;
import cn.wenzy.aurora.framework.support.i18n.I18nSupport;
import com.alibaba.fastjson2.filter.BeanContext;
import com.alibaba.fastjson2.filter.ContextValueFilter;
import lombok.AllArgsConstructor;

import java.lang.reflect.Field;

/**
 * 数据国际化转换
 */
@AllArgsConstructor
public class I18nContextValueFilter implements ContextValueFilter {
    private  I18nSupport i18nSupport;

    @Override
    public Object process(BeanContext beanContext, Object entity, String currentFieldName, Object currentFieldValue) {
        if (ObjectUtil.hasNull(beanContext, beanContext.getField(), entity, currentFieldName)) {
            return currentFieldValue;
        }
        Field currentField = beanContext.getField();
        I18nField i18nField = currentField.getAnnotation(I18nField.class);
        if (ObjectUtil.isNull(i18nField)) {
            return currentFieldValue;
        }
        String prefix = i18nField.prefix();
        String keyField = i18nField.keyField();

        prefix = StrUtil.addSuffixIfNot(prefix, StrUtil.DOT);
        Object fieldValue = BeanUtil.getFieldValue(entity, keyField);

        String i18nCode = prefix.concat(ObjectUtil.isNull(fieldValue) ? StrUtil.NULL : fieldValue.toString());
        String message = i18nSupport.getMessage(i18nCode);
        if (StrUtil.isBlank(message)) {
            return currentFieldValue;
        }
        return message;
    }

}
